package com.zhiqin.generateCode.util.gen;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.zhiqin.generateCode.dto.ColumnDto;
import com.zhiqin.generateCode.dto.GenTableInfoDto;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;
import java.util.List;

/**
 * @author zhiqin
 * @version V1.0
 * @Title: generate-code
 * @Package com.zhiqin.generateCode.util
 * @Description:
 * @date 2021/12/10 17:56
 */
public class MapperGen {

    public static void gen(List<ColumnDto> cloumnList, GenTableInfoDto genTableInfoDto) {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();

        //模板文件所在的classpath的路径
        Template t = ve.getTemplate("/vm/Mapper.xml.vm", "UTF-8");

        //填充数据
        VelocityContext ctx = new VelocityContext();
        ctx.put("columnList", cloumnList);
        ctx.put("entity", StrUtil.toCamelCase("_" + genTableInfoDto.getTable()));
        ctx.put("table", genTableInfoDto.getTable());
        ctx.put("tableName", StrUtil.toCamelCase(StrUtil.removePrefix(genTableInfoDto.getTable(), StrUtil.sub(genTableInfoDto.getTable(), 0, genTableInfoDto.getTable().indexOf("_")))));
        ctx.put("tableNameRemovePrefix", genTableInfoDto.getTable().substring(genTableInfoDto.getTable().indexOf("_")));
        ctx.put("author", genTableInfoDto.getAuthor());
        ctx.put("createTime", DateUtil.now());

        //输出流对象
        StringWriter sw = new StringWriter();
        t.merge(ctx, sw);
        System.out.println(sw.toString());
    }
}
